import '../../public.dart';
import 'components/balance_display_widget.dart';
import 'components/amount_input_widget.dart';
import 'components/bank_card_selector_widget.dart';
import 'components/pin_input_dialog.dart';
import 'components/bank_card_selector_dialog.dart';
import 'components/withdraw_button_widget.dart';
import 'components/no_bank_card_view_widget.dart';

class WithdrawPage extends StatefulWidget {
  const WithdrawPage({super.key});

  @override
  State<WithdrawPage> createState() => _WithdrawPageState();
}

class _WithdrawPageState extends State<WithdrawPage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _amountController = TextEditingController();

  WithdrawBankCardComboxDto? _selectedBankCard;
  bool _isLoading = false;

  @override
  void dispose() {
    _amountController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Withdraw'), centerTitle: true),
      body: SafeArea(
        child: ProviderWidget<UserModel>(
          builder: (context, model, child) {
            if (!model.isInit) {
              return const Center(child: CircularProgressIndicator());
            }

            // 检查是否有银行卡
            if (model.bankCardList.isEmpty) {
              return NoBankCardViewWidget(model: model);
            }

            return SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 账户余额展示
                    BalanceDisplayWidget(model: model),
                    const SizedBox(height: 24),

                    // 提现金额
                    AmountInputWidget(
                      controller: _amountController,
                      model: model,
                    ),
                    const SizedBox(height: 20),

                    // 银行卡选择
                    FormField<WithdrawBankCardComboxDto>(
                      validator: (value) {
                        if (_selectedBankCard == null) {
                          return 'Please select a bank card';
                        }
                        return null;
                      },
                      builder:
                          (FormFieldState<WithdrawBankCardComboxDto> state) {
                            return BankCardSelectorWidget(
                              selectedBankCard: _selectedBankCard,
                              onBankCardChanged: (card) {
                                setState(() {
                                  _selectedBankCard = card;
                                });
                                // 清除错误状态
                                state.didChange(card);
                              },
                              onTapSelector: () =>
                                  _showBankCardSelector(model, state),
                              errorText: state.hasError
                                  ? state.errorText
                                  : null,
                            );
                          },
                    ),
                    const SizedBox(height: 32),

                    // 提现按钮
                    WithdrawButtonWidget(
                      isLoading: _isLoading,
                      onPressed: () => _handleWithdrawButton(model),
                    ),
                  ],
                ),
              ),
            );
          },
          model: Provider.of<UserModel>(context),
        ),
      ),
    );
  }

  // 处理提现按钮点击 - 先验证表单再显示PIN弹窗
  Future<void> _handleWithdrawButton(UserModel model) async {
    if (_formKey.currentState?.validate() ?? false) {
      _formKey.currentState?.save();

      await PinInputDialog.show(
        context: context,
        onConfirm: (pin) => _handleWithdraw(model, pin),
      );
    }
  }

  // 处理提现
  Future<void> _handleWithdraw(UserModel model, String pin) async {
    if (_isLoading) return;

    final amount = double.tryParse(_amountController.text) ?? 0;
    final balance = model.availableBalance;

    // 验证金额
    if (amount < 1000) {
      Toast.show('Minimum withdraw amount is ₦1000');
      return;
    }

    if (amount > balance) {
      Toast.show('Amount cannot exceed available balance');
      return;
    }

    if (_selectedBankCard?.bankCardId == null) {
      Toast.show('Please select a bank card');
      return;
    }

    if (pin.length != 4) {
      Toast.show('Please enter a 4-digit PIN');
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final withdrawDto = ClientWithdrawDto(
        withdrawAmount: amount.toInt(),
        bankCardId: _selectedBankCard!.bankCardId!,
        pin: pin,
      );

      await ClientWithdrawApi.withdraw(withdrawDto);

      // 显示成功弹窗
      if (mounted) {
        BrnDialogManager.showSingleButtonDialog(
          context,
          title: 'SUCCESS',
          showIcon: true,
          message: 'Withdraw successful',
          label: 'OK',
          onTap: () {
            Navigator.of(context).pop(); // 关闭弹窗
          },
        );
      }

      // 清空表单
      _amountController.clear();
      setState(() {
        _selectedBankCard = null;
      });
      // 刷新余额
      await model.getBalance();
    } catch (e) {
      Toast.show('Withdraw error: $e');
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  // 显示银行卡选择器弹窗
  void _showBankCardSelector(
    UserModel model,
    FormFieldState<WithdrawBankCardComboxDto> state,
  ) async {
    final selectedCard = await BankCardSelectorDialog.show(
      context: context,
      bankCardList: model.bankCardList,
      selectedBankCard: _selectedBankCard,
    );

    if (selectedCard != null) {
      setState(() {
        _selectedBankCard = selectedCard;
      });
      // 清除验证错误状态
      state.didChange(selectedCard);
    }
  }
}
